﻿using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using NPOI.SS.Formula.Atp;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Http;
using System.Security.Policy;
using System.ServiceModel.Channels;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Windows.Forms;

namespace CloudApiServer.Controllers
{
    /// <summary>
    /// 浙江医保其他服务控制器
    /// </summary>
    [RoutePrefix("hsa-ims-svc/api")]
    public class FsiApiZheJiangHsaImsSvcController : ApiController
    {
        /*接口*/
        /// <summary>
        /// 医保接口没找到的统一接口返回
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        public IHttpActionResult FsiNotFound(HttpRequestMessage request)
        {
            string url = request.RequestUri.ToString();
            string Method = request.Method.ToString();
            string Errnum = LogHelper.GetErrornumber();
            try
            {
                if (string.IsNullOrEmpty(request.Content.ReadAsStringAsync().Result))
                {
                    FsiHsaImsSvcHeader<string> FsiHeader = new FsiHsaImsSvcHeader<string>
                    {
                        code=-1,
                        type="info",
                        message = $"[{Errnum}]调用浙江医保hsa-ims-svc自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加且入参为空！当前请求入参：" + request.Content.ReadAsStringAsync().Result
                    };
                    return Json(FsiHeader);
                }
                else
                {
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputSignIn>>(request.Content.ReadAsStringAsync().Result);
                    string infno = fsiRequest.infno;
                    FsiHsaImsSvcHeader<string> FsiHeader = new FsiHsaImsSvcHeader<string>
                    {
                        code = -1,
                        type = "info",
                        message = $"[{Errnum}]调用浙江医保hsa-ims-svc自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加！当前请求的接口号：{infno},当前请求入参：" + request.Content.ReadAsStringAsync().Result
                    };
                    return Json(FsiHeader);
                }
            }
            catch (JsonReaderException)
            {
                FsiHsaImsSvcHeader<string> FsiHeader = new FsiHsaImsSvcHeader<string>
                {
                    code = -1,
                    type = "info",
                    message = $"[{Errnum}]调用浙江医保hsa-ims-svc自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加且入参格式不正确！服务端无法正常反序列化！请检查入参是否为Json格式！当前请求入参：" + request.Content.ReadAsStringAsync().Result
                };
                return Json(FsiHeader);

            }
            catch (Exception ex)
            {
                FsiHsaImsSvcHeader<string> FsiHeader = new FsiHsaImsSvcHeader<string>
                {
                    code = -1,
                    type = "info",
                    message = $"[{Errnum}]调用浙江医保hsa-ims-svc自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加且服务端程序处理异常！请联系管理员排查！当前异常提示：{ex.Message},当前请求入参：" + request.Content.ReadAsStringAsync().Result
                };
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// ZJ3100 近90日购药明细查询接口
        /// </summary>
        /// <returns></returns>
        [Route("escessPharmacyScenService/queryDrugdosage")]
        [HttpPost]
        public async Task<IHttpActionResult> queryDrugdosage(HttpRequestMessage request)
        {

            DataTable dt = new DataTable();
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputQueryDrugdosageRequest>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    int pageSize = fsiRequest.Input.pageSize;
                    int currentPage = fsiRequest.Input.currentPage;
                    if (currentPage<=0||pageSize<=0)
                    {
                        throw new Exception("传入的pageSize(页容)|currentPage(页参)存在小于等于0的情况，请调整参数!");
                    }
                    string psn_no = fsiRequest.Input.psnNo;
                    string psn_name = fsiRequest.Input.psnName;
                    //获取当前时间前90天的时间
                    string datetime = DateTime.Now.AddDays(-90).ToString("yyyy-MM-dd HH:mm:ss");
                    if (psn_no == ""||psn_name=="")
                    {
                        throw new Exception("传入的psnno(人员编号)|psn_name(人员姓名)为空！");
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    //当前分页的最大页数
                    int maxpage = (int)((currentPage - 1) * pageSize);
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "SELECT a.mdtrtId,a.feeOcurTime,a.hiListCode,b.reg_name  as hiListName ,a.cnt,b.drug_dosform as dosformName,a.usedFrquDscr,a.sinDosDscr,a.`listType`, a.`medinsListCodg`, a.`medinsListName`, a.`medChrgitmType`, a.`chrgitmLv`, a.`pric`, a.`detItemFeeSumamt`, a.`inscpAmt`, a.`bilgDrCode`, a.`bilgDrName`, a.`ds`,c.certno FROM fsi_querydrugdosag a left join ml_xyzcyml b  on a.hiListCode=b.med_list_codg left join fsi_psninfo c on a.psnno=c.psn_no" +
                            " where a.psnno=@psnno and a.hiListCode like @hiListCode and b.reg_name  like @hiListName and a.feeOcurTime>=@datetime order by a.feeOcurTime desc limit @maxpage,@pagesize ";
                        cmd.Parameters.AddWithValue("@psnno", psn_no);
                        cmd.Parameters.AddWithValue("@hiListCode", "%"+fsiRequest.Input.hiListCode+"%");
                        cmd.Parameters.AddWithValue("@hiListName", "%" + fsiRequest.Input.hiListName + "%");
                        cmd.Parameters.AddWithValue("@maxpage", maxpage);
                        cmd.Parameters.AddWithValue("@pagesize", pageSize);
                        cmd.Parameters.AddWithValue("@datetime", datetime);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            dt.Load(reader);

                            cmd.CommandText = "SELECT count(*) FROM fsi_querydrugdosag a left join ml_xyzcyml b  on a.hiListCode=b.med_list_codg" +
                            " where a.psnno=@psnno and a.hiListCode like @hiListCode and b.reg_name  like @hiListName and a.feeOcurTime>=@datetime ";
                            object result = await cmd.ExecuteScalarAsync(); 
                            int count = Convert.ToInt32(result);

                            List<FsiHsaImsSvcOuputQueryDrugdosageDataList> dataList = new List<FsiHsaImsSvcOuputQueryDrugdosageDataList>();
                            int index = 1; 
                            foreach (DataRow row in dt.Rows)
                            {
                                FsiHsaImsSvcOuputQueryDrugdosageDataList item = new FsiHsaImsSvcOuputQueryDrugdosageDataList
                                {
                                    mdtrtId=row["mdtrtId"].ToString(),
                                    feeOcurTime = row["feeOcurTime"].ToString(),
                                    hilistCode = row["hiListCode"].ToString(),
                                    hiListName = row["hiListName"].ToString(),
                                    cnt = (decimal)row["cnt"],
                                    dosformName = row["dosformName"].ToString(),
                                    usedFrquDscr = row["usedFrquDscr"].ToString(),
                                    sinDosDscr=row["sinDosDscr"].ToString(),
                                    seq=index,
                                    certno=row["certno"].ToString(),
                                    listType=row["listType"].ToString(),
                                    medinsListCodg=row["medinsListCodg"].ToString(),
                                    medinsListName=row["hiListName"].ToString(),
                                    medChrgitmType=row["medChrgitmType"].ToString(),
                                    chrgitmLv=row["chrgitmLv"].ToString(),
                                    pric = (decimal)row["pric"],
                                    detItemFeeSumamt = (decimal)row["detItemFeeSumamt"],
                                    inscpAmt = (decimal)row["inscpAmt"],
                                    bilgDrCode =row["bilgDrCode"].ToString(),
                                    bilgDrName=row["bilgDrName"].ToString(),
                                    ds=row["ds"].ToString(),

                                };
                                dataList.Add(item);
                                index++; 
                            }
                            Random rnd = new Random();
                            DateTime dateTime = DateTime.Now;
                            var FsiHeader = new FsiHsaImsSvcHeader<FsiHsaImsSvcOuputQueryDrugdosageData>
                            {
                                data = new FsiHsaImsSvcOuputQueryDrugdosageData
                                {
                                    lists=dataList,
                                    total= count,
                                    pageSize=pageSize,
                                    currentPage=currentPage,
                                    psnNo=psn_no,
                                    psnName=psn_name
                                },
                                code = 0,
                                type = "success",
                                message = "成功",
                            };
                            return Json(FsiHeader);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHsaImsSvcHeader<string>
                    {
                        code = -1,
                        type = "info",
                        message = $"[{Errnum}]调用浙江医保hsa-ims-svc自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                    };
                    LogHelper.Error( $"[{Errnum}]调用浙江医保hsa-ims-svc自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }
    }
}
